'use client'

import request from '@/utils/frontend/request'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons'
import { Button, Input, Modal, Table, type TableProps, message } from 'antd'
import { useEffect, useState } from 'react'
import { formatGender } from '@/utils/frontend/format'
import { useRouter } from 'next/navigation'
import { useWebSocket } from '@/hooks/useWebSocket'
import { WSMessageType } from '@/types/ws'
import { useChatStore } from '@/store/chat'

interface UserSearchResult {
	id: number
	username: string
	nickname: string
	avatar: string | null
	status: 'online' | 'offline'
	gender: string
}

interface PaginationState {
	current: number
	pageSize: number
	total: number
}

// 好友列表的列定义
const getFriendColumns = (onChat: (id: number) => void, onDelete: (id: number) => void) => {
	const router = useRouter()

	return [
		{
			title: '用户名',
			dataIndex: 'username',
			key: 'username',
		},
		{
			title: '昵称',
			dataIndex: 'nickname',
			key: 'nickname',
		},
		{
			title: '性别',
			dataIndex: 'gender',
			key: 'gender',

			render: (gender: Gender) => formatGender(gender),
		},
		{
			title: '状态',
			dataIndex: 'status',
			key: 'status',
			render: (status: string) => (
				<span className={status === 'online' ? 'text-green-500' : 'text-gray-500'}>
					{status === 'online' ? '在线' : '离线'}
				</span>
			),
		},
		{
			title: '操作',
			key: 'action',
			width: 160,
			render: (_, record: UserSearchResult) => (
				<div className="space-x-2">
					<Button type="link" size="small" onClick={() => onChat(record.id)}>
						聊天
					</Button>
					<Button type="link" danger size="small" onClick={() => onDelete(record.id)}>
						删除
					</Button>
				</div>
			),
		},
	]
}

export default function MyFriend() {
	const [messageApi, contextHolder] = message.useMessage()
	const [pagination, setPagination] = useState<PaginationState>({
		current: 1,
		pageSize: 10,
		total: 0,
	})
	const [searchText, setSearchText] = useState('')
	const [loading, setLoading] = useState(false)
	const [friendList, setFriendList] = useState<UserSearchResult[]>([])
	// 添加好友弹窗状态
	const [addModalOpen, setAddModalOpen] = useState(false)
	const [searchUserText, setSearchUserText] = useState('')
	const [searching, setSearching] = useState(false)
	const [searchResults, setSearchResults] = useState<User[]>([])
	const [allUsers, setAllUsers] = useState<User[]>([])
	const router = useRouter()
	const { frontendSendWsEvent } = useWebSocket()

	// 获取好友列表
	const fetchFriendList = async (
		page = pagination.current,
		pageSize = pagination.pageSize,
		keyword = searchText
	) => {
		try {
			setLoading(true)
			const params = new URLSearchParams({
				page: String(page),
				pageSize: String(pageSize),
				keyword,
			})

			const { data } = (await request.get(`/friend?${params}`)) as ApiResponse
			setFriendList(data.list)
			setPagination((prev) => ({
				...prev,
				current: data.pagination.current,
				total: data.pagination.total,
			}))
		} catch (error) {
			messageApi.error('获取好友列表失败，请稍后重试')
		} finally {
			setLoading(false)
		}
	}

	// 首次加载获取好友列表
	useEffect(() => {
		fetchFriendList()
	}, [])

	// 修改 useEffect，添加来源判断

	// 处理分页变化
	const handleTableChange: TableProps<UserSearchResult>['onChange'] = (
		pagination,
		filters,
		sorter
	) => {
		const { current, pageSize } = pagination
		fetchFriendList(current, pageSize)
	}

	// 处理搜索
	const handleSearch = (value: string) => {
		setSearchText(value)
		fetchFriendList(1, pagination.pageSize, value)
	}

	// 处理搜索框变化
	const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		setSearchText(e.target.value)
	}

	// 处理添加好友
	const handleAddFriend = async () => {
		try {
			setSearching(true)
			// 获取所有用户列表
			const { data } = (await request.get('/user')) as ApiResponse
			setAllUsers(data.list)
			setAddModalOpen(true)
		} catch (error) {
			Modal.error({
				title: '获取用户列表失败',
				content: '请稍后重试',
			})
		} finally {
			setSearching(false)
		}
	}

	// 处理搜索用户（本地搜索）
	const handleSearchUser = (value: string) => {
		setSearchUserText(value)
		if (!value.trim()) {
			setSearchResults([])
			return
		}

		// 在已获取的用户列表中搜索
		const results = allUsers.filter(
			(user) =>
				user.username.toLowerCase().includes(value.toLowerCase()) ||
				user.nickname.toLowerCase().includes(value.toLowerCase())
		)
		setSearchResults(results)
	}

	// 处理发送好友请求
	const handleSendRequest = async (receiverId: number) => {
		try {
			const { success, message } = (await request.post('/friend/request', {
				receiverId,
			})) as ApiResponse

			if (success) {
				messageApi.success(message)

				setAddModalOpen(false)
				setSearchUserText('')
				setSearchResults([])
			} else {
				messageApi.error(message)
			}
		} catch (error) {
			messageApi.error(error as string)
		}
	}

	// 处理聊天
	const handleChat = async (friendId: number) => {
		try {
			// 发送创建私聊房间
			frontendSendWsEvent(WSMessageType.PRIVATE_CHAT, {
				friendId,
			})
		} catch (error) {
			messageApi.error('创建聊天失败，请重试')
		}
	}

	// 处理删除好友
	const handleDeleteFriend = (id: number) => {
		// 实现删除好友的逻辑
		console.log('删除好友', id)
	}

	return (
		<div className="space-y-4">
			{contextHolder}
			{/* 顶部操作区域 */}
			<div className="flex justify-between items-center">
				<div className="w-80">
					<Input.Search
						placeholder="搜索好友..."
						allowClear
						size="large"
						enterButton={<SearchOutlined />}
						onSearch={handleSearch}
						onChange={handleSearchChange}
						value={searchText}
					/>
				</div>
				<Button type="primary" icon={<PlusOutlined />} size="large" onClick={handleAddFriend}>
					添加好友
				</Button>
			</div>

			{/* 好友列表 */}
			<Table
				columns={getFriendColumns(handleChat, handleDeleteFriend)}
				dataSource={friendList}
				rowKey="id"
				loading={loading}
				pagination={{
					...pagination,
					showSizeChanger: true,
					showQuickJumper: true,
					showTotal: (total) => `共 ${total} 条记录`,
				}}
				onChange={handleTableChange}
			/>

			{/* 添加好友弹窗 */}
			<Modal
				title="添加好友"
				open={addModalOpen}
				onCancel={() => {
					setAddModalOpen(false)
					setSearchUserText('')
					setSearchResults([])
				}}
				footer={null}
				maskClosable={false}
				centered
				width="30vw"
			>
				<div className="py-5">
					<Input.Search
						placeholder="输入用户名或昵称搜索..."
						loading={searching}
						size="large"
						enterButton
						onSearch={handleSearchUser}
						onChange={(e) => handleSearchUser(e.target.value)}
						value={searchUserText}
					/>
					{searchResults.length > 0 && (
						<div className="max-h-80 overflow-y-auto">
							{searchResults.map((user) => (
								<div key={user.id} className="flex items-center justify-between p-4 border-b">
									<div className="flex items-center gap-2">
										<div className="font-medium">{user.nickname}</div>
										<div className="text-gray-500 text-sm">{user.username}</div>
										<div className="text-gray-500 text-sm">{formatGender(user.gender)}</div>
									</div>
									<Button type="primary" size="small" onClick={() => handleSendRequest(user.id)}>
										发送请求
									</Button>
								</div>
							))}
						</div>
					)}
					{searchUserText && !searching && searchResults.length === 0 && (
						<div className="text-center text-gray-500 py-4">未找到相关用户</div>
					)}
				</div>
			</Modal>
		</div>
	)
}
